/* eslint-disable react/prop-types */
import React, { memo, useState, useEffect } from 'react'
import { Upload, Modal, message } from 'antd'
import {
  PlusOutlined,
  EyeOutlined,
  DeleteOutlined,
} from '@ant-design/icons'
import { multipartUpload, getOssPreviewUrl } from '@/utils/oss'
import s from './style.module.scss'

function UploadFileFC (props) {

  const {
    fileList = [],
    setFileList,
    fileType,
    mode,
    plural = false, // 是否可以上传多张
    maxCount = 1,
    tipsContent,
  } = props

  const [acceptFileType, setAcceptFileType] = useState('')
  const [mimeList, setMimeList] = useState([])
  const [ossPath, setOssPath] = useState('')
  const [loading, setLoading] = useState(false)
  const [customList, setCustomList] = useState([])

  const config = {
    accept: acceptFileType,
    name: 'uploadFile',
    showUploadList: false,
    beforeUpload (file) {
      if (!mimeList.includes(file.type)) {
        message.error('请上传正确的文件格式！')
        return Promise.reject()
      }
    },
    customRequest (options) {
      if (loading) return false
      const { file } = options
      console.log(file)

      if (mode === 'oss') {
        setLoading(true)
        multipartUpload(file, ossPath).then((res) => {
          console.log(res)
          if (!res) return
          let tempList = [...fileList]
          let param = {
            uid: file.uid,
            name: file.name,
            status: 'done',
            url: res.url
          }
          tempList.push(param)
          console.log(tempList)
          setFileList(tempList)
          setCustomList(tempList)
        }).finally(() => setLoading(false))
      }
    }
  }

  const removeFileItem = (index) => {
    if (fileList[index]) {
      let _list = JSON.parse(JSON.stringify(fileList))
      _list.splice(index, 1)
      setFileList(_list)
      setCustomList(_list)
    }
  }

  // img 显示状态
  const [previewVisible, setPreviewVisible] = useState(false)
  // img title
  const [imgTitle, setImgTitle] = useState('')
  const [path, setPath] = useState('')
  const checkFileItem = (url, item) => {
    if (url) {
      let signatureUrl = getOssPreviewUrl(url)
      console.log(signatureUrl)
      setPreviewVisible(true)
      setPath(url)
      setImgTitle(item.name)
    }
  }

  const handleCancel = () => {
    setPreviewVisible(false)
  }

  const judgeCanUpload = () => ((!plural && customList.length) || (plural && customList.length === maxCount))

  useEffect(() => {
    setAcceptFileType('.jpg,.jpeg,.png,.gif,.svg,.JPG,.JPEG,.PNG,.GIF,.SVG',)
    setMimeList(['image/png', 'image/jpeg', 'image/jpg', 'image/gif', 'image/svg+xml'])
    setOssPath('image')
  }, [])

  useEffect(() => {
    if (fileList.length) {
      let count = 0
      let tempArr = fileList.map(item => ({
        uid: String(--count),
        name: item.name,
        status: 'done',
        url: item.url || ''
      }))
      setCustomList(tempArr)
    }
    // eslint-disable-next-line
  }, [fileList])

  return (
    <>
      {
        fileType === 'image' &&
        <div>
          <div className={s.uploadImgBox}>
            {customList.length > 0 &&
            customList.map((item, index) => (
              <div className={s.previewBox} key={`thumb_${index}`}>
                <img className={s.thumb} src={item.url} alt=""/>
                <div className={s.maskBox}>
                  <div className={s.iconBox}>
                    <EyeOutlined className={s.icon} onClick={() => checkFileItem(item.url, item)} />
                    <DeleteOutlined className={s.icon} onClick={() => removeFileItem(index)} />
                  </div>
                </div>
              </div>
            ))
            }
            {judgeCanUpload() ?
              null :
              <Upload  {...config}  maxCount={1} listType="picture-card" fileList={customList}>
                <PlusOutlined />
              </Upload>
            }
           
          </div>
          {tipsContent?.length && <div className={s.tipsContent}>{tipsContent}</div>}
        </div>
      }
      <Modal
        visible={previewVisible}
        title={imgTitle}
        footer={null}
        onCancel={handleCancel}
        zIndex={99999}
      >
        <img alt="example" style={{ width: '100%' }} src={path} />
      </Modal>
    </>
  )
}

export default memo(UploadFileFC)